/**
 * 文件管理器 - 处理账户文件的浏览和管理
 */
class FileManager {
    constructor() {
        this.currentPath = '/';
        this.files = [];
        this.folders = [];
        this.selectedItem = null;
        this.init();
    }

    init() {
        this.bindEvents();
        this.initTabs();
    }

    bindEvents() {
        // 选项卡切换
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('tab-btn')) {
                this.switchTab(e.target.dataset.tab);
            }
        });

        // 登录提示按钮
        const promptLoginBtn = document.getElementById('prompt-login-btn');
        if (promptLoginBtn) {
            promptLoginBtn.addEventListener('click', () => {
                if (window.authManager) {
                    window.authManager.showLoginModal();
                }
            });
        }

        // 文件操作按钮
        const newFolderBtn = document.getElementById('new-folder-btn');
        const uploadFileBtn = document.getElementById('upload-file-btn');

        if (newFolderBtn) {
            newFolderBtn.addEventListener('click', () => this.createNewFolder());
        }

        if (uploadFileBtn) {
            uploadFileBtn.addEventListener('click', () => this.uploadFile());
        }

        // 监听认证状态变化
        document.addEventListener('authStateChanged', (e) => {
            this.handleAuthStateChange(e.detail.isAuthenticated);
        });
    }

    initTabs() {
        // 默认显示本地文件选项卡
        this.switchTab('local-files');
    }

    switchTab(tabName) {
        // 移除所有活动状态
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });

        // 激活选中的选项卡
        const tabBtn = document.querySelector(`[data-tab="${tabName}"]`);
        const tabContent = document.getElementById(tabName);

        if (tabBtn && tabContent) {
            tabBtn.classList.add('active');
            tabContent.classList.add('active');

            // 如果切换到账户文件，检查登录状态
            if (tabName === 'account-files') {
                this.checkAccountFilesAccess();
            }
        }
    }

    handleAuthStateChange(isAuthenticated) {
        const loginPrompt = document.getElementById('account-login-prompt');
        const fileTree = document.getElementById('account-file-tree');

        if (isAuthenticated) {
            loginPrompt.style.display = 'none';
            fileTree.style.display = 'block';
            this.loadAccountFiles();
        } else {
            loginPrompt.style.display = 'block';
            fileTree.style.display = 'none';
        }
    }

    checkAccountFilesAccess() {
        const isAuthenticated = window.authManager && window.authManager.isAuthenticated();
        this.handleAuthStateChange(isAuthenticated);
    }

    async loadAccountFiles(path = '/') {
        try {
            this.currentPath = path;
            const treeContent = document.getElementById('account-tree-content');
            treeContent.innerHTML = '<span>加载中...</span>';

            // 模拟API调用
            const response = await this.mockApiCall('/api/user/files', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                }
            });

            if (response.success) {
                this.renderFileTree(response.data);
            } else {
                this.showError('加载文件失败: ' + response.message);
            }
        } catch (error) {
            console.error('加载账户文件失败:', error);
            this.showError('加载文件失败');
        }
    }

    renderFileTree(data) {
        const treeContent = document.getElementById('account-tree-content');
        
        if (!data || (!data.folders && !data.files)) {
            treeContent.innerHTML = '<div class="empty-folder">此文件夹为空</div>';
            return;
        }

        let html = '';

        // 如果不在根目录，显示返回上级按钮
        if (this.currentPath !== '/') {
            html += `
                <div class="file-item folder-item" data-type="parent">
                    <div class="file-item-content">
                        <span class="file-icon">📁</span>
                        <span class="file-name">..</span>
                    </div>
                </div>
            `;
        }

        // 渲染文件夹
        if (data.folders) {
            data.folders.forEach(folder => {
                html += `
                    <div class="file-item folder-item" data-type="folder" data-name="${folder.name}" data-path="${folder.path}">
                        <div class="file-item-content">
                            <span class="file-icon">📁</span>
                            <span class="file-name">${folder.name}</span>
                        </div>
                        <div class="file-item-actions">
                            <button class="file-action-btn" data-action="rename" title="重命名">✏️</button>
                            <button class="file-action-btn" data-action="delete" title="删除">🗑️</button>
                        </div>
                    </div>
                `;
            });
        }

        // 渲染文件
        if (data.files) {
            data.files.forEach(file => {
                const fileIcon = this.getFileIcon(file.name);
                html += `
                    <div class="file-item file-item-file" data-type="file" data-name="${file.name}" data-path="${file.path}">
                        <div class="file-item-content">
                            <span class="file-icon">${fileIcon}</span>
                            <span class="file-name">${file.name}</span>
                            <span class="file-size">${this.formatFileSize(file.size)}</span>
                        </div>
                        <div class="file-item-actions">
                            <button class="file-action-btn" data-action="download" title="下载">⬇️</button>
                            <button class="file-action-btn" data-action="rename" title="重命名">✏️</button>
                            <button class="file-action-btn" data-action="delete" title="删除">🗑️</button>
                        </div>
                    </div>
                `;
            });
        }

        treeContent.innerHTML = html;
        this.bindFileEvents();
    }

    bindFileEvents() {
        const treeContent = document.getElementById('account-tree-content');
        
        treeContent.addEventListener('click', (e) => {
            const fileItem = e.target.closest('.file-item');
            if (!fileItem) return;

            const type = fileItem.dataset.type;
            const name = fileItem.dataset.name;
            const path = fileItem.dataset.path;

            if (e.target.classList.contains('file-action-btn')) {
                const action = e.target.dataset.action;
                this.handleFileAction(action, { type, name, path });
                return;
            }

            // 处理文件/文件夹点击
            if (type === 'parent') {
                this.navigateUp();
            } else if (type === 'folder') {
                this.navigateToFolder(path);
            } else if (type === 'file') {
                this.openFile(path);
            }
        });
    }

    async handleFileAction(action, item) {
        switch (action) {
            case 'rename':
                await this.renameItem(item);
                break;
            case 'delete':
                await this.deleteItem(item);
                break;
            case 'download':
                await this.downloadFile(item);
                break;
        }
    }

    async createNewFolder() {
        const name = prompt('请输入文件夹名称:');
        if (!name) return;

        try {
            const response = await this.mockApiCall('/api/user/files/folder', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: name,
                    path: this.currentPath
                })
            });

            if (response.success) {
                this.showSuccess('文件夹创建成功');
                this.loadAccountFiles(this.currentPath);
            } else {
                this.showError('创建文件夹失败: ' + response.message);
            }
        } catch (error) {
            console.error('创建文件夹失败:', error);
            this.showError('创建文件夹失败');
        }
    }

    async uploadFile() {
        const input = document.createElement('input');
        input.type = 'file';
        input.multiple = true;
        
        input.onchange = async (e) => {
            const files = Array.from(e.target.files);
            if (files.length === 0) return;

            for (const file of files) {
                await this.uploadSingleFile(file);
            }
            
            this.loadAccountFiles(this.currentPath);
        };

        input.click();
    }

    async uploadSingleFile(file) {
        try {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('path', this.currentPath);

            // 注意：这里应该使用真实的文件上传API
            const response = await fetch('/api/user/files/upload', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: formData
            });

            if (response.ok) {
                this.showSuccess(`文件 ${file.name} 上传成功`);
            } else {
                this.showError(`文件 ${file.name} 上传失败`);
            }
        } catch (error) {
            console.error('上传文件失败:', error);
            this.showError(`文件 ${file.name} 上传失败`);
        }
    }

    navigateUp() {
        const parentPath = this.currentPath.split('/').slice(0, -1).join('/') || '/';
        this.loadAccountFiles(parentPath);
    }

    navigateToFolder(path) {
        this.loadAccountFiles(path);
    }

    async openFile(path) {
        try {
            const response = await this.mockApiCall(`/api/user/files/content?path=${encodeURIComponent(path)}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (response.success) {
                // 在编辑器中打开文件内容
                if (window.editor) {
                    window.editor.setValue(response.data.content);
                }
                this.showSuccess('文件已打开');
            } else {
                this.showError('打开文件失败: ' + response.message);
            }
        } catch (error) {
            console.error('打开文件失败:', error);
            this.showError('打开文件失败');
        }
    }

    getFileIcon(filename) {
        const ext = filename.split('.').pop().toLowerCase();
        const iconMap = {
            'md': '📝',
            'txt': '📄',
            'pdf': '📕',
            'doc': '📘',
            'docx': '📘',
            'xls': '📗',
            'xlsx': '📗',
            'ppt': '📙',
            'pptx': '📙',
            'jpg': '🖼️',
            'jpeg': '🖼️',
            'png': '🖼️',
            'gif': '🖼️',
            'zip': '📦',
            'rar': '📦',
            'js': '📜',
            'html': '🌐',
            'css': '🎨',
            'json': '📋'
        };
        return iconMap[ext] || '📄';
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    }

    // 模拟API调用
    async mockApiCall(url, options = {}) {
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 500));

        // 模拟不同的API响应
        if (url === '/api/user/files') {
            return {
                success: true,
                data: {
                    folders: [
                        { name: 'Documents', path: '/Documents' },
                        { name: 'Projects', path: '/Projects' }
                    ],
                    files: [
                        { name: 'README.md', path: '/README.md', size: 1024 },
                        { name: 'notes.txt', path: '/notes.txt', size: 512 }
                    ]
                }
            };
        }

        return { success: true, data: {} };
    }

    showSuccess(message) {
        if (window.showToast) {
            window.showToast(message, 'success');
        } else {
            alert(message);
        }
    }

    showError(message) {
        if (window.showToast) {
            window.showToast(message, 'error');
        } else {
            alert(message);
        }
    }
}

// 初始化文件管理器
document.addEventListener('DOMContentLoaded', () => {
    window.fileManager = new FileManager();
});